<template>
	<view class="container">
		<video :src="videoSrc" :show-center-play-btn="false" ref="video" :controls="false"></video>
	</view>
</template>

<script>
	import urlConfig from "@/request/urlConfig.js";
	export default {
		data() {
			return {
				videoSrc: '',
				video: '',
				imgUrl: '',
				option: {}
			};
		},
		onLoad(option) {
			this.option = option
		},
		mounted() {
			this.video = document.querySelector('video')
			console.log(this.video, "viede");
			this.connectCamera();
		},
		methods: {
			nav() {
				uni.$emit('back', "11111111")
				uni.navigateBack()
			},
			connectCamera(groupId) {
				navigator.mediaDevices.getUserMedia({
						video: true
					})
					.then((stream) => {
						this.video.srcObject = stream;
						this.video.onloadedmetadata = (e) => {
							this.video.play();
							setTimeout(() => {
								this.canvas1()
							}, 2000)
						};
					})
					.then((devices) => {
						// 处理设备列表
						console.log(devices);
					})
					.catch((err) => {
						console.error('获取设备失败:', err);
					});
			},
			connectCamera2(groupId) {
				console.log(groupId, "groupid");
				navigator.mediaDevices
					.getUserMedia({
						video: {
							groupId,
							width: 1080,
							height: 800
						},
					})
					.then((stream) => {
						console.log(stream, 'stream');
						this.video.srcObject = stream;
						// 定时五秒自动拍照
						this.video.onloadedmetadata = (e) => {
							this.video.play();
							setTimeout(() => {
								this.canvas1()
							}, 5000)
						};
					})
					.catch(console.log);
			},
			async canvas1() {
				let video = document.getElementsByTagName("video")[0] // 获取video节点
				let canvas = document.createElement("canvas") // 创建canvas节点
				let w = video?.clientWidth
				let h = video?.clientHeight
				console.log(video,":video");
				console.log(w,h);
				canvas.width = 600	
				canvas.height = 800 // 设置宽高
				const ctx = canvas.getContext("2d")
				ctx?.drawImage(video, 0, 0, w, h) // video写入到canvas  clientHeight
				let imgUrl = canvas.toDataURL("image/png") // 生成截图地
				console.log(imgUrl, "imgUrl");
				this.imgUrl = this.dataURLtoBlob(imgUrl)
				console.log(this.dataURLtoBlob(imgUrl));
				try {
					const a = await this.uploadFilePromises(imgUrl, this.option.id)
					if (a.state == 1) {
						// this[key][idx].fileUrl = a.userSign
						this.option.url = a.userSign
						uni.$emit('back', this.option)
						uni.navigateBack()
					} else {
						setTimeout(() => {
							uni.$u.toast(a.message)
						}, 500);
						uni.navigateBack()
					}
				} catch (e) {
					console.log();
					setTimeout(() => {
						uni.$u.toast('对比失败')
					}, 500);
					uni.navigateBack()
					//TODO handle the exception
				}

			},
			uploadFilePromises(url, id) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: urlConfig.baseURL + '/wsd/operateOrder/checkFileImages', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							userId: id
						},
						header: {
							'User-Token': uni.getStorageSync('token') || "",
						},
						success: (res) => {
							console.log(res, "res");
							setTimeout(() => {
								resolve(JSON.parse(res.data)
									.datas)
							}, 1000)
						}
					});
				})
			},
			dataURLtoBlob(dataurl) {
				let arr = dataurl.split(","),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n)
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n)
				}
				return new Blob([u8arr], {
					type: mime
				})
			},
		}
	};
</script>

<style>
	.container {}

	video {
		width: 100%;
		height: 100vh;
		object-fit: cover;
	}

	.scan {
		/* 初始位置在水平居中 */
		width: 200px;
		/* 横条的宽度 */
		height: 1px;
		/* background-color: #00CD66; */
		/* animation: scan 5s linear infinite; */
		position: absolute;
		z-index: 1000000000000000;
		left: 25%;
		top: 30%;
		box-shadow: 0 -4px 10px #00CD66;
		/* 内部阴影效果，从底部边框往上 */
		border-bottom: 1px solid #00CD66;
		/* 底部边框 */
		/* 内部阴影效果 */
	}

	.scan::before {}

	@keyframes scan {
		0% {
			top: 0;
		}

		50% {
			top: 100%;
			/* 在50%时移动到底部 */
		}

		50.1% {
			top: -100%;
			/* 略微延迟，回到顶部 */
		}

		100% {
			top: 0;
			/* 完成一次扫描，回到起始位置 */
		}
	}
</style>